using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Repositories;

namespace Lzfy_Refund_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class DictController : ControllerBase
    {
        private readonly IRefundDictRepository _dictRepository;

        public DictController(IRefundDictRepository dictRepository)
        {
            _dictRepository = dictRepository;
        }

        /// <summary>
        /// 获取所有字典数据
        /// </summary>
        /// <returns>字典数据列表</returns>
        [HttpPost("get-all")]
        public async Task<ActionResult<IEnumerable<RefundDict>>> GetAllDicts()
        {
            var dicts = await _dictRepository.GetAllAsync();
            return Ok(dicts);
        }

        /// <summary>
        /// 根据字典ID获取字典项
        /// </summary>
        /// <param name="request">包含字典ID的请求</param>
        /// <returns>字典项列表</returns>
        [HttpPost("get-by-dict-id")]
        public async Task<ActionResult<IEnumerable<RefundDict>>> GetDictsByDictId([FromBody] GetByDictIdRequest request)
        {
            var dicts = await _dictRepository.GetByDictIdAsync(request.DictId);
            return Ok(dicts);
        }

        /// <summary>
        /// 根据ID获取字典项详情
        /// </summary>
        /// <param name="request">包含字典项ID的请求</param>
        /// <returns>字典项详情</returns>
        [HttpPost("get-by-id")]
        public async Task<ActionResult<RefundDict>> GetDictById([FromBody] GetByIdRequest request)
        {
            var dict = await _dictRepository.GetByIdAsync(request.Id);
            if (dict == null)
            {
                return NotFound(new { message = "字典项不存在" });
            }

            return Ok(dict);
        }

        /// <summary>
        /// 创建字典项
        /// </summary>
        /// <param name="request">字典项创建请求</param>
        /// <returns>创建的字典项ID</returns>
        [HttpPost]
        public async Task<ActionResult<int>> CreateDict([FromBody] RefundDictCreateRequest request)
        {
            try
            {
                var dict = new RefundDict
                {
                    DictId = request.DictId,
                    DictName = request.DictName,
                    ItemName = request.ItemName,
                    ItemValue = request.ItemValue
                };

                var dictId = await _dictRepository.CreateAsync(dict);
                return CreatedAtAction(nameof(GetDictById), new { id = dictId }, new { id = dictId });
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = "创建字典项失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 更新字典项
        /// </summary>
        /// <param name="request">字典项更新请求（包含ID）</param>
        /// <returns>更新结果</returns>
        [HttpPost("update")]
        public async Task<ActionResult> UpdateDict([FromBody] RefundDictUpdateRequest request)
        {
            try
            {
                var existingDict = await _dictRepository.GetByIdAsync(request.Id);
                if (existingDict == null)
                {
                    return NotFound(new { message = "字典项不存在" });
                }

                existingDict.DictId = request.DictId;
                existingDict.DictName = request.DictName;
                existingDict.ItemName = request.ItemName;
                existingDict.ItemValue = request.ItemValue;

                var success = await _dictRepository.UpdateAsync(existingDict);
                if (!success)
                {
                    return BadRequest(new { message = "更新字典项失败" });
                }

                return Ok(new { message = "更新成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = "更新字典项失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 新增字典项（原PUT方法）
        /// </summary>
        /// <param name="id">字典项ID</param>
        /// <param name="request">字典项创建请求</param>
        /// <returns>创建结果</returns>
        [HttpPut("{id}")]
        public async Task<ActionResult> CreateDictWithId(int id, [FromBody] RefundDictCreateRequest request)
        {
            try
            {
                var existingDict = await _dictRepository.GetByIdAsync(id);
                if (existingDict == null)
                {
                    return NotFound(new { message = "字典项不存在" });
                }

                existingDict.DictId = request.DictId;
                existingDict.DictName = request.DictName;
                existingDict.ItemName = request.ItemName;
                existingDict.ItemValue = request.ItemValue;

                var success = await _dictRepository.UpdateAsync(existingDict);
                if (!success)
                {
                    return BadRequest(new { message = "更新字典项失败" });
                }

                return Ok(new { message = "更新成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = "更新字典项失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 删除字典项
        /// </summary>
        /// <param name="id">字典项ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteDict(int id)
        {
            try
            {
                var success = await _dictRepository.DeleteAsync(id);
                if (!success)
                {
                    return NotFound(new { message = "字典项不存在" });
                }

                return Ok(new { message = "删除成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = "删除字典项失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取附件类型字典 (dict_id = 1)
        /// </summary>
        /// <returns>附件类型列表</returns>
        [HttpPost("get-attach-types")]
        public async Task<ActionResult<IEnumerable<RefundDict>>> GetAttachTypes()
        {
            var attachTypes = await _dictRepository.GetByDictIdAsync(1);
            return Ok(attachTypes);
        }

        /// <summary>
        /// 获取退款类型字典 (dict_id = 2)
        /// </summary>
        /// <returns>退款类型列表</returns>
        [HttpPost("get-refund-types")]
        public async Task<ActionResult<IEnumerable<RefundDict>>> GetRefundTypes()
        {
            var refundTypes = await _dictRepository.GetByDictIdAsync(2);
            return Ok(refundTypes);
        }

        /// <summary>
        /// 获取审核类型字典 (dict_id = 3)
        /// </summary>
        /// <returns>审核类型列表</returns>
        [HttpPost("get-audit-types")]
        public async Task<ActionResult<IEnumerable<RefundDict>>> GetAuditTypes()
        {
            var auditTypes = await _dictRepository.GetByDictIdAsync(3);
            return Ok(auditTypes);
        }

        /// <summary>
        /// 获取与患者关系字典 (dict_id = 4)
        /// </summary>
        /// <returns>与患者关系列表</returns>
        [HttpPost("get-patient-relations")]
        public async Task<ActionResult<IEnumerable<RefundDict>>> GetPatientRelations()
        {
            var relations = await _dictRepository.GetByDictIdAsync(4);
            return Ok(relations);
        }

        /// <summary>
        /// 获取字典分类列表
        /// </summary>
        /// <returns>字典分类列表</returns>
        [HttpPost("get-dict-categories")]
        public async Task<ActionResult<IEnumerable<DictCategory>>> GetDictCategories()
        {
            var categories = await _dictRepository.GetDictCategoriesAsync();
            return Ok(categories);
        }
    }
}